import { parseExcel } from '~~/server/utils/excel'
import { db } from '~~/server/db'
import { createCaseSchema, casesTable, batchImportSchema } from '~~/server/db/schema/case'
import { fromError } from 'zod-validation-error'

export default defineEventHandler(async (event) => {
  const validationResult = await readValidatedBody(event, (body) =>
    batchImportSchema.safeParse(body)
  )
  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }
  try {
    const formData = await readMultipartFormData(event)

    const file = formData?.find((field) => field.name === 'file')
    if (!file) {
      throw createError({
        statusCode: 400,
        statusMessage: '文件不能为空'
      })
    }
    const excelData = await parseExcel<CaseExcelData>(file)
    const validatedRows = []
    for (let i = 0; i < excelData.length; i++) {
      const item = excelData[i]
      const rowData = {
        clientName: item.委托方,
        plaintiff: item.诉讼主体,
        batch: item.批次,
        litigationTeam: item.诉讼组,
        legalAssistant: item.律师助理,
        mediator: item.调解员,
        orderId: item.订单编号,
        orderType: item.订单类型,
        name: item.姓名,
        idCard: item.身份证,
        phone: item.手机号,
        address: item.户籍地址,
        lender: item.放款方,
        guarantor: item.担保方,
        overduePrincipal: item.逾期本金,
        caseStatus: item.案件状态,
        court: item.法院
      }
      const validationResult = await readValidatedBody(event, () =>
        createCaseSchema.safeParse(rowData)
      )
      if (!validationResult.success) {
        throw createError({
          statusCode: 400,
          message: fromError(validationResult.error).toString()
        })
      }
      validatedRows.push(validationResult)
    }
    for (let i = 0; i < validatedRows.length; i++) {
      const {
        court = '',
        orderId,
        batch,
        clientName,
        plaintiff,
        name,
        idCard,
        phone,
        address,
        lender,
        guarantor,
        overduePrincipal,
        litigationTeam,
        legalAssistant,
        mediator,
        orderType,
        caseStatus
      } = validatedRows[i].data
      await db.insert(casesTable).values({
        court,
        orderId,
        batch,
        clientName,
        plaintiff,
        name,
        idCard,
        phone,
        address,
        lender,
        guarantor,
        overduePrincipal,
        litigationTeam,
        legalAssistant,
        mediator,
        orderType,
        caseStatus
      })
    }
  } catch (error) {
    // 错误处理
    const errorMessage = error instanceof Error ? error.message : '解析Excel文件时发生未知错误'
    throw createError({
      statusCode: 500,
      statusMessage: errorMessage
    })
  }
})
